<?php
// questo script aggiunge nella tabella manufacturer_to_store
// le marche inserite non presenti
 
// Configuration
require_once('../config.php');

define ('DIR_IMAGE_PRODUCT', DIR_IMAGE .'data/product/' );
define ('DIR_IMAGE_LOAD', DIR_SYSTEM . '../var/caricamento/image/' );

$file_log = '';

if ( count($argv) ) {
	$file_log = $argv[1];
}

define ('FILE_LOG',   $file_log);

// Startup
require_once(DIR_SYSTEM . 'startup.php');

// Config
$config = new Config();

// Database
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

require_once('common.php');

$queryStr = "select * from product_load where elab_chk = 0";

$product_load = $db->query($queryStr);

if ($product_load->num_rows) {
	
  LogBatch::getInstance()->write('Ci sono prodotti '. $product_load->num_rows .' caricati sulla product_load');

  $insertStr = "INSERT INTO product( model,
                     sku,
                     upc,
                     location,
                     quantity,
                     stock_status_id,
                     image,
                     manufacturer_id,
                     shipping,
                     price,
                     points,
                     tax_class_id,
                     date_available,
                     weight,
                     weight_class_id,
                     length,
                     width,
                     height,
                     length_class_id,
                     subtract,
                     minimum,
                     sort_order,
                     status,
                     date_added,
                     date_modified,
                     viewed
                )
          VALUES
                (
                  '%s',
                  '',
                  '',
                  '',
                  0,
                  %d,
                  null,
                  %s,
                  1,
                  0,
                  0,
                  %d,
                  '%s',
                  '%s',
                  1,
                  '%s',
                  '%s',
                  '%s',
                  1,
                  0,
                  0,
                  0,
                  %d,
                  now(),
                  now(),
                  0
              )";

  // conserviamoci l'id dell'iva
  $queryStr = "SELECT tax_class_id FROM tax_class WHERE title = 'Iva 21%'";
  $iva = $db->query($queryStr);
  $tax_class_id = $iva->rows[0]['tax_class_id'];

	foreach ($product_load->rows as $product) {
	
//    model, name, image, category_code, manufacturer_code, date_available, 
//    weight, length, width, height, status, stock_status_id

		$model              = $product['model'];
		$name               = $product['name'];
		$description        = $product['description'];  
		$image              = $product['image'];
		$category_code      = $product['category_code'];
		$manufacturer_code  = $product['manufacturer_code'];
		$date_available     = $product['date_available'];
		$weight             = $product['weight'];
    $length             = $product['length'];
    $width              = $product['width'];
    $height             = $product['height'];
    $status             = $product['status'];
    $stock_status_id    = $product['stock_status_id'];

    $name               = $db->escape($name);
    $description        = $db->escape($description);
    $manufacturer_code  = $db->escape($manufacturer_code);
    $category_code      = $db->escape($category_code);

    // si tratta di un nuovo inserimento
    LogBatch::getInstance()->write('Inserisco il nuovo prodotto  ='. $model);

    // inserisco la categoria
    $queryStr = sprintf( $insertStr, 
                              $model, 
                              $stock_status_id,
                              "(select manufacturer_id from manufacturer where manufacturer_code = '$manufacturer_code')",
                              $tax_class_id,
                              $date_available,
                              $weight,
                              $length,
                              $width,
                              $height,
                              $status
                          );
    $db->query($queryStr);
    $product_id = $db->getLastId();

    // insert sulla product_to_category    
    $queryStr = "insert into product_to_category values ( $product_id, 
                  (select category_id from category_description where category_code = '$category_code') )";	
    $db->query($queryStr);	

    // insert sulla product_to_store    
    $queryStr = "insert into product_to_store values ( $product_id, 0 )";	
    $db->query($queryStr);	
    
    // insert sulla product_description
    $queryStr = "INSERT INTO product_description
                (
                  `product_id`,
                  `language_id`,
                  `name`,
                  `description`,
                  `meta_description`,
                  `meta_keyword`
                )
                VALUES
                (
                  $product_id, 
                  $language_id,
                  '$name',
                  '$description',
                  '',
                  ''
                )";
    $db->query($queryStr);
    
    // Aggiungo la gestione della image
    if ( $image != '' ) { // se il nome dell'image e' valorizzato

      $imageNew = $image;

      // LogBatch::getInstance()->write('Image = ['. $image.']');

      if ( file_exists ( DIR_IMAGE_LOAD . $image ) ) {

        LogBatch::getInstance()->write('L\'image = ['. $image. '] del prodotto esiste nella directory di caricamento');

        // image esiste nella directory caricamento ... verifico se esiste
        // nel sistema un'image con lo stesso nome ...
        if ( file_exists ( DIR_IMAGE_PRODUCT . $image ) ) {
          LogBatch::getInstance()->write('L\'image = ['. $image. '] esiste nella directory di '.DIR_IMAGE_PRODUCT.' la rinomino ...');
          $imageNew = $model.'_'.$image; // aggiungo il codice categoria
        }

        // LogBatch::getInstance()->write('Image ='. $image);
      }

      // copiare l'image
      if (!@copy(DIR_IMAGE_LOAD . $image, DIR_IMAGE_PRODUCT . $imageNew)) {
        LogBatch::getInstance()->write('Fallito copia della image ='. $image. ' nella cartella di sistema');
      } else {
        $image = 'data/product/'. $imageNew;
        $image    = $db->escape($image);
        $queryStr = "UPDATE product set image = '$image' where product_id = $product_id";
        $db->query($queryStr);
      }
    } // end if ( $image != '' )
	
	}

  LogBatch::getInstance()->write('Aggiorno tutti i record sulla product_load ');

  $db->query("update product_load set elab_chk = 1 where elab_chk = 0");
	
} else {
  LogBatch::getInstance()->write('Non ci sono prodotti caricati sulla product_load');
}
